﻿using DemoCore.Configuration;
using DemoCore.Hosts;
using DemoCore.Routings;
using System;
using System.Configuration;
using System.ServiceModel;

namespace HostA
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (ServiceHost host = new ServiceHost(typeof(SayHello)))
                {
                    host.Opened += (s, e) =>
                    {
                        Console.WriteLine("8081服务启动成功...");
                    };
                    host.Open();
                    RegisterToRoutingService();
                    Console.Read();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }
        }

        static void RegisterToRoutingService()
        {
            var configSection = ConfigurationManager.GetSection("platform") as FilterSections;
            var channel = new ChannelFactory<IHost>(configSection.Server.MainHostEndpoint);

            foreach (AddressElement host in configSection.Server.MainHostCollection)
            {
                try
                {
                    channel.CreateChannel(new EndpointAddress(host.BaseAddress)).RegisterHost(new SubHost
                    {
                        Address = configSection.Server.Address,
                        Performance = configSection.Server.Performance
                    });
                    Console.WriteLine("8081服务注册：" + host.BaseAddress);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("8081服务注册失败...", ex);
                }
            }
        }
    }
}
